package concurrecy.util;


import java.util.Random;
import java.util.concurrent.*;


public class CyclicBarrierDemo {
    public static void main(String[] args) {
        CyclicBarrier cyclicBarrier = new CyclicBarrier(3, () -> {
            System.out.println("barrier action");
        });
        Random random = new Random();
        ExecutorService service = Executors.newCachedThreadPool();
        for(int i = 0; i < 6; i ++)
            service.execute(() -> {
                try {
                    TimeUnit.MILLISECONDS.sleep(random.nextInt(10000));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + " await");
                try {
                    cyclicBarrier.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + " exit");
            });
        service.shutdown();
    }
}
